<template>
    <div>
        <div class="topCard">
            <span><i class="el-icon-time"></i> {{timer}}</span>
            <span @click="seeList"><i class="el-icon-menu"></i>查看</span>
            <div class="qlist" v-show="isOpenQList">
                <template v-for="(v,index) in answers">
                    <span v-if="v.type==1||v.type==3" class="list-item" :class="{active: v.answer[0]}" @click="clickQList(index)">{{index+1}}</span>
                    <span v-if="v.type==2" class="list-item" :class="{active: v.answer[0]}" @click="clickQList(index)">{{index+1}}</span>
                    <span v-if="v.type==4" class="list-item" :class="{active: v.answer2[0].val}" @click="clickQList(index)">{{index+1}}</span>
                </template>
            </div>
        </div>
        <el-card class="box-card">
            <div slot="header" class="clearfix">
                <span>{{qSort+1}}.</span>
                <span>{{qList[qSort].content}}</span>
                <span>({{qList[qSort].type|typeFilter}})</span>
                <!--<el-button style="float: right; padding: 3px 0" type="text">操作按钮</el-button>-->
            </div>

            <!--单选项-->
            <template v-if="qList[qSort].type==1">
                <div v-for="(v,index) in qList[qSort].option" :key="index" class="text item">
                    <el-radio v-model="answers[qSort].answer" :label="abc[index]" @change="chooseRadio">{{abc[index]}}. {{v[abc[index]]}}</el-radio>
                </div>
            </template>
            <!--多选项-->
            <template v-if="qList[qSort].type==2">
                <div v-for="(v,index) in qList[qSort].option" :key="index" class="text item">
                    <el-checkbox v-model="answers[qSort].answer" :label="abc[index]">{{abc[index]}}. {{v[abc[index]]}}</el-checkbox>
                </div>
            </template>
            <!--判断题-->
            <template v-if="qList[qSort].type==3">
                <el-radio-group v-model="answers[qSort].answer">
                    <el-radio label="Y" value="Y">正确</el-radio>
                    <el-radio label="N" value="N">错误</el-radio>
                </el-radio-group>
            </template>
            <!--填空题-->
            <template v-if="qList[qSort].type==4">
                <i style="color: red;font-size: 0.8rem;">提示：依次输入答案</i>
                <template v-for="(v,index) in answers[qSort].answer2">
                    <el-input type="text" placeholder="输入答案" v-model="v.val" style="margin-bottom: 5px;"></el-input>
                </template>
                <div class="addInps">
                    <i class="el-icon-circle-plus addInp" @click="addInp"></i>
                    <i class="el-icon-remove addInp" @click="delInp" style="color: #888;"></i>
                </div>
            </template>
        </el-card>
        <div class="bottom-btn">
            <el-button-group style="width: 100%;display: flex;">
                <el-button type="default" icon="el-icon-arrow-left" @click="pre">上一题</el-button>
                <el-button type="primary" @click="next">下一题<i class="el-icon-arrow-right el-icon--right"></i></el-button>
                <el-button type="success" @click="done">答题完成，提交试卷</el-button>
                <!--v-show="isDone"-->
            </el-button-group>
        </div>
    </div>
</template>

<script>
    export default {
        name: "exam",
        data(){
            return{
                questionBankId: '', // 试卷id
                userTestPaperId: '', // 答题记录的id
                abc: ['A','B','C','D','E','F','G','H','I','J','K','L','M','N'],
                qSort: 0,
                answers: [{
                    answer: [],
                    answer2: [{val: ''}]
                }],

                isOpenQList: false,
                qList: [
                    {
                        id: '',
                        content: '',
                        type: '0',
                        option: [{val: 'jfkdjf'},{val: 'jfkdjf'},{val: 'jfkdjf'},{val: 'jfkdjf'}],
                        sort: 0,
                    }
                ], // 本试卷获取到的试题列表

                isDone: false, // 是否完成答题

                timer: '', // 答题剩余时间
                tt: 0, // 定时器返回

                qlong: 99,  // 总题数

                getSuccess: false, // 是否创建试卷
            }
        },
        filters: {
            typeFilter(inp){
                let str = '';
                if(inp=='1') str='单选';
                if(inp=='2') str='多选';
                if(inp=='3') str='判断';
                if(inp=='4') str='填空';
                return str;
            }
        },
        methods:{
            loadopen() {
                this.loading = this.$loading({
                    lock: true,
                    text: 'Loading',
                    spinner: 'el-icon-loading',
                    background: 'rgba(0, 0, 0, 0.2)'
                });
                setTimeout(() => {this.loading.close();}, 5000);
            },
            loadclose() {
                this.loading.close();
            },
            // 单选选择触发事件
            chooseRadio(val){
                setTimeout(s=>{
                    this.next();
                }, 300);
            },
            // 查看所有获取到的题答题情况
            seeList(){
                this.isOpenQList = !this.isOpenQList;
                // if(this.isOpenQList){
                //     this.findTestPage();
                // }
            },
            // 查询所有题
            findTestPage(){
                this.loadopen();
                this.config.appPost('/user/examination/findTestPaper', {
                    questionBankId: this.questionBankId,
                }).then(res => {
                    this.loadclose();
                    if(res.data.code === '0'){
                        this.qList = res.data.questionList;
                    }else if(res.data.code === '-2001'){
                        this.$router.push('/examLogin');
                    }else {
                        this.$message.error(res.data.message);
                    }
                });
            },
            // 上一题
            pre(){
                if(this.qSort>0) {
                    this.qSort = this.qSort-1;
                    // this.question = this.qList[this.qSort];
                }
            },
            // 下一题
            next(){
                if(this.qSort<(this.qList.length)) {
                    // this.answers.push({
                    //     answer: [],
                    //     answer2: [{val: ''}]
                    // });
                    // this.qSort = this.qSort+1;
                    // if(this.qSort===(this.qList.length-1)) this.isDone = true;
                    this.submitQus();
                }
            },
            // 点击列表直达题目
            clickQList(index){
                this.qSort = index;
                this.isOpenQList = false;
                if(this.qSort===(this.qList.length-1)) this.isDone = true;
            },
            // 添加填空输入框
            addInp(){this.answers[this.qSort].answer2.push({val: ''});},
            // 移除填空输入框
            delInp(){if(this.answers[this.qSort].answer2.length<2) return;this.answers[this.qSort].answer2.pop();},
            // 生成试卷
            creatPaper(){
                this.loadopen();
                this.config.appPost('/user/testpaper/createTestPaper', {
                    modeId: this.questionBankId,
                }).then(res => {
                    this.loadclose();
                    if(res.data.code === '0'){
                        this.getQus();
                        this.getSuccess = true;
                    }else if(res.data.code == '-1003'){
                        this.$message.error(res.data.message);
                        this.$router.push({path: '/examDone', query: {questionBankId: this.questionBankId, userTestPaperId: this.userTestPaperId}})
                    }else {
                        this.$message.error(res.data.message);
                    }
                });
            },
            // 获取所有考试题目
            getQus(){
                this.loadopen();
                this.config.appPost('/user/testpaper/getTestPager', {
                    modeId: this.questionBankId,
                    userTestPaperId: this.userTestPaperId,
                }).then(res => {
                    this.loadclose();
                    if(res.data.code === '0'){
                        if(res.data.questionList.length){
                            this.timerCount(res.data); // 去计算剩余时间
                            this.qList = res.data.questionList;
                            this.qList.forEach(it=>{
                                it.option = JSON.parse(it.option)||{};
                                let aas = [], aas2=[];
                                // 如果已经答过此题
                                if(it.answer_time){
                                    aas = JSON.parse(it.user_answer);
                                    if(it.type=='1'||it.type=='3') aas = aas[0]||'';
                                    if(it.type=='4'){
                                        aas.forEach(y=>{
                                            aas2.push({
                                                val: y||''
                                            })
                                        })
                                    }
                                }
                                this.answers.push({
                                    id: it.testpaper_id,
                                    type: it.type,
                                    answer: it.answer_time?(it.type=='4'?[]:aas):[],
                                    answer2: it.answer_time?(it.type=='4'?aas2:[{val: ''}]):[{val: ''}]
                                });
                            });
                            this.answers.shift();
                        }else{
                            if(!this.getSuccess){
                                this.creatPaper();
                            }
                        }
                    }else if(res.data.code === '-2001'){
                        this.$router.push('/examLogin');
                    }else if(res.data.code==='-1002'){
                        this.$router.push({path: '/examDone', query: {questionBankId: this.questionBankId, score: res.data.score}});
                        this.$message.success(res.data.message);
                    }else {
                        this.$message.error(res.data.message);
                    }
                });
            },
            // 提交答案
            submitQus(){
                let ans = {}; // this.qList[this.qSort]
                let cqus = this.answers[this.qSort];  // 当前题
                if(cqus.type=='1'||cqus.type=='3'){
                    ans = {
                        anwser: typeof(cqus.answer)==='string'?[cqus.answer]:[]
                    }
                }
                if(cqus.type=='2'){
                    ans = {
                        anwser: (cqus.answer).sort()
                    }
                }
                if(cqus.type=='4'){
                    let ss = [];
                    cqus.answer2.forEach(y=>{
                        ss.push(y.val)
                    });
                    ans = {
                        anwser: ss
                    }
                }
                if(this.qSort===(this.qList.length-1)){
                    if(!ans.anwser[0]) {alert('最后一题，请作答');return}
                }
                this.loadopen();
                this.config.appPost('/user/testpaper/submitQuestion', {
                    id: this.qList[this.qSort].testpaper_id,
                    answer: JSON.stringify(ans),
                }).then(res => {
                    this.loadclose();
                    if(res.data.code === '0'){
                        if(this.qSort===(this.qList.length-1)) {
                            this.isDone = true
                        }
                        if(this.qSort<(this.qList.length-1)){
                            this.qSort = this.qSort+1;
                        }
                    }else if(res.data.code === '-2001'){
                        this.$router.push('/examLogin');
                    }else {
                        this.$message.error(res.data.message);
                    }
                });
            },
            // 提交答题开始时间
            getStartTime(){
                this.loadopen();
                this.config.appPost('/user/examination/getStartTime', {
                    questionBankId: this.questionBankId,
                }).then(res => {
                    this.loadclose();
                    if(res.data.code === '0'){
                        clearInterval(this.tt);
                        this.timerCount(res.data.time);
                    }else if(res.data.code === '-2001'){
                        this.$router.push('/examLogin');
                    }else {
                        // this.$message.error(res.data.message);
                    }
                });
            },
            // 倒计时计算方法
            clock(timerStr){
                var h = Math.floor(timerStr/(3600*1000));
                var mstr = timerStr%(3600*1000);
                var m = Math.floor(mstr/(60*1000));
                var sStr = timerStr%(60*1000);
                var s = Math.floor(sStr/1000);
                function ext(t){
                    return t<10?('0'+t):t;
                }
                return ext(h)+':'+ext(m)+':'+ext(s);
            },
            // 倒计时
            timerCount(data){
                // let startStr = new Date().getTime();
                // let startStr = new Date(data.questionList[0].start_time).getTime(); // 开始时间
                let startStr = Date.parse((data.questionList[0].start_time).replace(/-/g,"/")); // 开始时间
                this.tt = setInterval(s=>{
                    let nowStr = new Date().getTime(); // 当前时间
                    // let timerStr = startStr+(2*3600*1000) - nowStr;
                    let timerStr = startStr+(data.total_answer_time*60*1000) - nowStr; // 计算剩余时间
                    if(timerStr<=0){
                        this.$message.warning('您的答题时间已结束！');
                        clearInterval(this.tt);
                        setTimeout(s=>{
                            this.done('2');
                        }, 500);
                        return;
                    }
                    this.timer = this.clock(timerStr);
                    this.jugeEndTime(nowStr); // 判断当前时间是否到达统一考试结束时间
                }, 1000)
            },
            // 判断当前时间是否到达统一考试结束时间
            jugeEndTime(currentTime){
                let examEndTime = sessionStorage.getItem('examEndTime')*1; // 获取试卷的结束时间
                if(currentTime>examEndTime){ // 如果当前时间大于试卷结束时间，则立刻结束考试
                    clearInterval(this.tt);
                    this.$message.warning('统一考试时间结束');
                    setTimeout(s=>{
                        this.done('2');
                    }, 500);
                }
            },
            // 答题完成，提交试卷
            done(num){
                if(!num){
                    let flag = false;
                    let bool = this.answers.some((it,index)=>{
                        if(it.type==='1') return !it.answer[0];
                        if(it.type==='2') return !it.answer[0];
                        if(it.type==='3') return !it.answer[0];
                        if(it.type==='4') return !it.answer2[0].val;
                    });
                    if(bool) {
                        this.$message.warning('还有未答完的题，点击右上击查看');
                        return;
                    }
                }
                this.loadopen();
                this.config.appPost('/user/testpaper/finishTest', {
                    modeId: this.questionBankId,
                    userTestPaperId: this.userTestPaperId,
                    // anwser: JSON.stringify(ans),
                }).then(res => {
                    this.loadclose();
                    if(res.data.code === '0'){
                        clearInterval(this.tt);
                        this.$message.success(res.data.message);
                        this.$router.push({path: '/examDone', query: {questionBankId: this.questionBankId, userTestPaperId: this.userTestPaperId}})
                    }else if(res.data.code === '-2001'){
                        this.$router.push('/examLogin');
                    }else {
                        this.$message.error(res.data.message);
                    }
                });
            }
        },
        mounted(){
            // 当前页面获取题库id
            let questionBankId = this.$route.query['questionBankId']||this.questionBankId;
            let userTestPaperId = this.$route.query['userTestPaperId']||this.userTestPaperId;
            if(questionBankId){
                this.questionBankId = questionBankId;
                this.userTestPaperId = userTestPaperId;
                this.getQus(0);
                // this.getStartTime();
            }
        }
    }
</script>

<style lang="less" scoped>
    .text {
        font-size: 14px;
    }

    .item {
        margin-bottom: 18px;
        border: 1px solid #eee;
        .el-radio,.el-checkbox{
            width: 100%;
            padding: 10px;
            /*line-height: 42px;*/
            line-height: 20px;
            text-indent: 0.5rem;
            font-size: 1rem;

            /*display: inline-grid;*/
            white-space: pre-line;
            word-wrap: break-word;
            overflow: hidden;
        }
    }
    .item:active{
        border: 1px solid #20a0ff;
    }

    .clearfix:before,
    .clearfix:after {
        display: table;
        content: "";
    }
    .clearfix:after {
        clear: both
    }

    .box-card {
        /*width: 480px;*/
    }

    /*上一题 下一题*/
    .bottom-btn{
        position: absolute;
        width: 100%;
        bottom: 0;
        left: 0;
        .el-button{
            width: 50%;
            height: 2.5rem;
        }
    }

    /*顶部card*/
    .topCard{
        display: flex;
        justify-content: space-between;
        padding: 0.8rem;
        color: #409EFF;
        position: relative;
    }
    /*顶部题目列表展示*/
    .qlist{
        position: absolute;
        width: 100%;
        min-height: 3rem;
        top: 3rem;
        left: 0;
        background: #eee;
        display: flex;
        flex-wrap: wrap;
        justify-content: center;
        padding: 1rem 0.2rem;
        box-sizing: border-box;
        z-index: 5;
        .list-item{
            /*display: inline-block;*/
            width: 2.2rem;
            height: 30px;
            line-height: 30px;
            text-align: center;
            border: 1px solid #409EFF;
            border-radius: 5rem;
            margin: 0.3rem;
        }
        .list-item.active{
            background: #409EFF;
            color: #fff;
        }
    }
    .addInps{
        display: flex;
        justify-content: space-between;
        .addInp{
            font-size: 2rem;
            margin: 1rem 0 0;
            color: #409EFF;
        }
    }

</style>
